package com.android.webserver.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.android.webserver.tornado.HTTP;
import com.android.webserver.tornado.HTTPException;
import com.android.webserver.tornado.Response;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * @author Baptiste GOURDIN
 *
 */
public class RawRessourceUtil
{
	public static void getPicture(Context context, Response response, int ressourceId) throws HTTPException
	{
		Bitmap image = BitmapFactory.decodeResource(context.getResources(), ressourceId);
		if (image != null)
		{
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.PNG, 100, stream);
			response.RawContent = stream.toByteArray();
			response.addHeader("Content-Length: " + response.RawContent.length);
			response.addHeader("Content-Type: " + "image/png");
			response.setHTTPStatusCode(HTTP.OK);
		}
		else
			throw new HTTPException(HTTP.NOT_FOUND);
	}
	
	public static void getRawTextFile(Context context, Response response, int ressourceId) throws HTTPException
	{
		InputStream inputStream = context.getResources().openRawResource(
				ressourceId);
		if (inputStream != null)
		{
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

			try
			{
				int i = inputStream.read();
				while (i != -1)
				{
					byteArrayOutputStream.write(i);
					i = inputStream.read();
				}
				inputStream.close();
				response.RawContent = byteArrayOutputStream.toByteArray();
				response.addHeader("Content-Length: " + response.RawContent.length);
				response.addHeader("Content-Type: " + "text/plain");
				response.setHTTPStatusCode(HTTP.OK);
			}
			catch (IOException e)
			{
				throw new HTTPException(HTTP.NOT_FOUND);
			}
		}
		else
			throw new HTTPException(HTTP.NOT_FOUND);
	}

}
